// DNS resolution utility functions

/**
 * Resolves a hostname to its IP address using a DNS lookup
 * @param {string} hostname - The hostname to resolve
 * @returns {Promise<string>} - The resolved IP address
 */
export const resolveHostname = async (hostname) => {
  try {
    // Remove protocol and path from URL if present
    const cleanHostname = hostname.replace(/^https?:\/\//, '').split('/')[0];
    
    // Check if input is already an IP address
    const ipRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
    if (ipRegex.test(cleanHostname)) {
      return cleanHostname;
    }

    // Use fetch to make a request to a DNS resolution API
    const response = await fetch(`https://dns.google/resolve?name=${cleanHostname}`);
    const data = await response.json();
    
    if (data.Answer && data.Answer.length > 0) {
      // Return the first IP address found
      return data.Answer[0].data;
    }
    
    throw new Error('No IP address found for the hostname');
  } catch (error) {
    throw new Error(`DNS resolution failed: ${error.message}`);
  }
}

/**
 * Validates if a string is a valid IP address
 * @param {string} ip - The string to validate
 * @returns {boolean} - True if valid IP address
 */
export const isValidIP = (ip) => {
  const ipRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
  return ipRegex.test(ip);
} 